<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Util;
use plugin\admin\app\constant\v1\CommonConstant;
use plugin\admin\app\model\V1Region;
use plugin\admin\app\model\V1Server;
use support\Request;
use support\Response;
use plugin\admin\app\model\V1NodeStatic;
use plugin\admin\app\model\V1NodeStaticTp;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;
use support\think\Db;
use think\Exception;

/**
 * 静态节点管理
 */
class V1NodeStaticController extends Crud
{

    /**
     * @var V1NodeStatic
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new V1NodeStatic;
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(Request $request): Response
    {
        $line_id = $request->input('line_id');
        $region_id = $request->input('region_id');
        $server_id = $request->input('server_id');
        return view('v1-node-static/index',compact('line_id','region_id','server_id'));
    }

    /**
     * 查询
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $where['deleted'] = CommonConstant::DELETE_0;
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {

            $params = $request->post();

            $name_array = getLineBreak($params['ip']);
            if (!$name_array) {
                return $this->fail('请输入节点编号|ip|端口|内网ip！');
            }

            $insert_data = [];
            $date = date('Y-m-d H:i:s');
            foreach ($name_array as $value) {
                $array = explode('|', $value);
                $array = getLineEmpty($array);

                if ($array) {
                    $port = $array[2] ?? '';
                    $ip_ems = $array[3] ?? '';
                    if(!empty($port) ){
                        $checkPortOrIp = checkPortOrIp($port);
                        if(!$checkPortOrIp){
                            $ip_ems = $port;
                            $port = '';
                        }
                    }

                    $data = [];
                    $data['line_id'] = $params['line_id'];
                    $data['region_id'] = $params['region_id'];
                    $data['server_id'] = $params['server_id'];
                    $data['code'] = $array[0] ?? '';
                    $data['ip'] = $array[1] ?? '';
                    $data['port'] = $port;
                    $data['ip_ems'] = $ip_ems;
                    $data['created_at'] = $date;
                    $data['line_id'] = $params['line_id'];
                    $insert_data[] = $data;
                }
            }
            if (!$insert_data) {
                return $this->fail('请输入节点编号|ip|端口|内网ip！');
            }

            Util::db()->transaction(function () use ($params, $insert_data) {
                $this->model->insert($insert_data);
            });
            $number = $this->model
                ->where('deleted', CommonConstant::DELETE_0)
                ->where('region_id', $params['region_id'])
                ->count('id');
            V1Region::where('id', $params['region_id'])->update(['ip_number' => $number]);
            $number2 = $this->model
                ->where('deleted', CommonConstant::DELETE_0)
                ->where('server_id', $params['server_id'])
                ->count('id');
            V1Server::where('id', $params['server_id'])->update(['ip_number' => $number2]);
            return $this->json(0);
//            return parent::insert($request);
        }
        return view('v1-node-static/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            [$id, $data] = $this->updateInput($request);
            $info = $this->model->find($id);
            if (!$info) {
                return $this->json(1, '节点数据不存在！');
            }

            $region_id_old = $info['region_id'];
            $server_id_old = $info['server_id'];
            doUpdate($data,$info);

            if($data['region_id'] != $region_id_old){
                $number_old = $this->model
                    ->where('deleted', CommonConstant::DELETE_0)
                    ->where('region_id', $region_id_old)
                    ->count('id');
                V1Region::where('id', $region_id_old)->update(['ip_number' => $number_old]);
            }
            if($data['server_id'] != $server_id_old){
                $number2_old = $this->model
                    ->where('deleted', CommonConstant::DELETE_0)
                    ->where('server_id', $server_id_old)
                    ->count('id');
                V1Server::where('id', $server_id_old)->update(['ip_number' => $number2_old]);
            }
            $number = $this->model
                ->where('deleted', CommonConstant::DELETE_0)
                ->where('region_id', $data['region_id'])
                ->count('id');
            V1Region::where('id', $data['region_id'])->update(['ip_number' => $number]);
            $number2 = $this->model
                ->where('deleted', CommonConstant::DELETE_0)
                ->where('server_id', $data['server_id'])
                ->count('id');
            V1Server::where('id', $data['server_id'])->update(['ip_number' => $number2]);
            return $this->json(0);
//            return parent::update($request);
        }
        return view('v1-node-static/update');
    }

    /**
     * 删除
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function delete(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $ids = $this->deleteInput($request);
            if (!$ids) {
                return $this->json(1, '参数错误！');
            }

            $list = V1NodeStaticTp::where('deleted', CommonConstant::DELETE_0)
                ->whereIn('id', $ids)
                ->field('region_id,count(id) as number')
                ->group('region_id')
                ->select()
                ->toArray();
            if (!$list) {
                return $this->json(1, '没有数据！');
            }
            $list2 = V1NodeStaticTp::where('deleted', CommonConstant::DELETE_0)
                ->whereIn('id', $ids)
                ->field('server_id,count(id) as number')
                ->group('server_id')
                ->select()
                ->toArray();
            Util::db()->transaction(function () use ($ids, $list, $list2) {
                foreach ($list as $value) {
                    V1Region::where('id', $value['region_id'])->decrement('ip_number', $value['number']);
                }
                foreach ($list2 as $value2) {
                    V1Server::where('id', $value2['server_id'])->decrement('ip_number', $value2['number']);
                }
                $primary_key = $this->model->getKeyName();
                $this->model->whereIn($primary_key, $ids)->update(['deleted' => CommonConstant::DELETE_1]);
            });
//            $this->doDeleted($ids);
            return $this->json(0);
        }
    }

    /**
     * 过期ip替换
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function replace(Request $request): Response
    {
        if ($request->method() === 'POST') {

            $params = $request->post();

            $name_array = getLineBreak($params['ip']);
            if (!$name_array) {
                return $this->fail('请输入节点编号|ip|端口|内网ip');
            }

            $error_array = [];
            $code_array = [];
            $new_array = [];
            foreach ($name_array as $value) {
                $array = explode('|', $value);
                $array = getLineEmpty($array);

                if ($array) {
                    if (!isset($array[1]) || empty($array[1])) {
                        $error_array[] = $array[0];
                        continue;
                    }
                    $new = [];
                    $new['ip'] = $array[1];
                    if (isset($array[2]) && !empty($array[2])) {
                        if (strpos($array[2], '.') !== false) {
                            $new['ip_ems'] = $array[2];
                        } else {
                            $new['port'] = $array[2];
                        }
                    }
                    if (isset($array[3]) && !empty($array[3])) {
                        $new['ip_ems'] = $array[3];
                    }
                    $code_array[] = $array[0];
                    $new_array[$array[0]] = $new;
                }
            }
            if ($error_array) {
                return $this->fail('节点编号：' . implode(',', $error_array) . ' 缺少ip数据');
            }
            if (!$new_array) {
                return $this->fail('请输入节点编号|ip|端口|内网ip！');
            }

            $list = V1NodeStaticTp::where('deleted', 0)
                ->where('code', 'IN', $code_array)
                ->select();
            $new_list = $list->toArray();
            if (!$new_list) {
                return $this->fail('节点编号：' . implode(',', $code_array) . ' 数据不存在');
            }
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    if (array_key_exists($item['code'], $new_array)) {
                        $item->save($new_array[$item['code']]);
                        unset($new_array[$item['code']]);
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return $this->json(1, $e->getMessage());
            }
            if ($new_array) {
                return $this->json(0, '替换成功，节点编号：' . implode(',', array_keys($new_array)) . ' 数据不存在', []);
            }
            return $this->json(0);
        }
        return view('v1-node-static/replace');
    }

}
